<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\ArticlesDraft;
use App\Constants\TagConstant;
use App\Models\Tag;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Tab;

class HotArticlesDraftController extends AdminController
{
    protected $title = '草稿箱';

    protected $translation = 'articles-draft';

    public function index(Content $content)
    {
        $tab = Tab::make();
        $tab->addLink('热点快讯', admin_route('hot_articles.index'));
        $tab->addLink('标签', admin_route('hot_news_tags.index'));
        $tab->add('草稿箱', $this->grid(), true);
        return $content->body($tab->withCard());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        Admin::translation('articles-draft');

        return Grid::make(new ArticlesDraft(['publisher', 'hot_news_tag']), function (Grid $grid) {
            $map = getAuthMiniProgramMap(Admin::user()->id);
            $grid->model()->whereIn('mini_type', array_keys($map))->where('type', '=', 1)->orderByDesc('id');

            $grid->column('id');
            $grid->column('mini_type')->display(function ($miniType) use ($map) {
                return $miniType ? $map[$miniType] : '';
            });
            $grid->column('publisher.name', '发布人');
            $grid->column('title');
            $grid->column('hot_news_tag.name', '标签');
            $grid->column('publish_date');
            $grid->column('status')->using(['未发布', '已发布'])->label(['danger', 'success']);
            $grid->column('created_at');

            $grid->disableFilterButton();
            $grid->disableRefreshButton();
            $grid->disableBatchDelete();
            $grid->disableViewButton();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) use ($map) {
                $filter->panel();
                $filter->expand();

                $filter->equal('id')->width(2);
                $filter->equal('mini_type')->select($map)->width(2);
                $filter->equal('status')->select(['未发布', '已发布'])->width(2);
                $filter->between('created_at')->datetime()->width(4);
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ArticlesDraft(), function (Show $show) {
            $show->field('id');
            $show->field('publish_id');
            $show->field('type');
            $show->field('title');
            $show->field('desc');
            $show->field('file_type');
            $show->field('files');
            $show->field('video');
            $show->field('thum_img');
            $show->field('content');
            $show->field('is_hot');
            $show->field('is_top');
            $show->field('first_relay_count');
            $show->field('first_fav_count');
            $show->field('tag_id');
            $show->field('mini_type');
            $show->field('publish_date');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ArticlesDraft(), function (Form $form) {
            $form->display('id');
            $form->select('publish_id')->options(publisher_options())->required()->customFormat(function (){
                return sprintf('%s|%s', $this->publish_id, $this->mini_type);
            });
            $form->hidden('type')->value(1);
            $form->text('title')->required();
            $form->select('tag_id', '标签')
                ->saving(function ($v) {
                    return (int)$v;
                })
                ->options(Tag::where('type', '=', TagConstant::TAG_BY_HOT_NEWS)->pluck('name', 'id')->all());

            $form->radio('file_type')
                ->when(1, function (Form $form) {
                    $form->multipleImage('files', ' ')->sortable()->uniqueName()
                        ->saving(function ($value) {
                            return implode(',', $value);
                        })->customFormat(function ($v) { // 转换为显示的格式
                            return $v;
                        })->limit(9)->saveFullUrl()->help('建议尺寸: 750X560PX');
                })
                ->when(2, function (Form $form) {
                    $form->file('video', ' ')->chunked()->chunkSize(1024 * 5)->maxSize(1024 * 2 * 1000)->autoUpload()->uniqueName()->saveFullUrl();
                    $form->image('thum_img', '视频封面')->uniqueName()->autoUpload()->saveFullUrl();
                })
                ->options([
                    1 => '图片',
                    2 => '视频',
                ])
                ->default(1);
            $form->textarea('content')->rules('required|string', [
                'required' => '内容必填',
            ]);
            $form->radio('is_hot')->options(['否', '是'])->default(0);
            $form->radio('is_top')->options(['否', '是'])->default(0);
            $form->text('first_relay_count')->default(0);
            $form->text('first_fav_count')->default(0);
            $form->hidden('mini_type');
            $form->datetime('publish_date')->format('YYYY-MM-DD HH:mm')->required();

            $form->display('created_at');
            $form->display('updated_at');

            $form->saving(function (Form $form){
                $file_type = $form->file_type;
                $thum_img = $form->thum_img;
                $files = $form->files;
                if ($file_type == 2 && !$thum_img) {
                    return $form->response()->error('视频封面必传');
                } elseif ($file_type == 1 && !$files) {
                    return $form->response()->error('素材图片必传');
                }

                if (strtotime($form->publish_date) <= time()) {
                    return $form->response()->error('发布时间必须大于当前时间');
                }

                [$publish_id, $mini_type] = explode('|', $form->publish_id);
                $form->publish_id = $publish_id;
                $form->mini_type = $mini_type;
            });
        });
    }
}
